package xuhaijia.lanou3g.autohome.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import xuhaijia.lanou3g.autohome.R;


/**
 * Created by dllo on 16/7/29.
 */
public class CircleImageView extends ImageView {

    private Paint mpaint;
    private boolean isCircle;

    public CircleImageView(Context context) {
        super(context);
        init();
    }

    public CircleImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public CircleImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView);
        isCircle = array.getBoolean(R.styleable.CircleImageView_isCircle, false);
    }

    public void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        mpaint = new Paint();
        mpaint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (isCircle) {
            Drawable drawable = getDrawable();
            drawable.setBounds(0, 0, getWidth(), getHeight());
            drawable.draw(canvas);
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas1 = new Canvas(bitmap);
            canvas1.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, paint);
            mpaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
            canvas.drawBitmap(bitmap, 0, 0, mpaint);
        } else {
            super.onDraw(canvas);
        }
    }
}
